package com.mtons.mblog.modules.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.mtons.mblog.base.utils.ObjectConvertUtils;
import com.mtons.mblog.modules.service.MailService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName: EmailMqHandler
 * @Auther: Jerry
 * @Date: 2020/5/15 9:48
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Component
public class EmailMqHandler {

    private Logger log = LoggerFactory.getLogger(EmailMqHandler.class);

    @Autowired
    private MailService mailService;

    @RabbitListener(queues = RabbitConstant.EMAIL_QUEUE)
    public void handler(Message message, Channel channel) throws IOException {
        EmailMqMessage emailMqMessage = (EmailMqMessage) ObjectConvertUtils.ByteToObject(message.getBody());

        log.info("EmailMqHandler -------> mq 收到一条消息： {}", JSONObject.toJSONString(emailMqMessage));
        mailService.sendTemplateEmail(emailMqMessage.getTo(), emailMqMessage.getTitle(),
                emailMqMessage.getTemplate(), emailMqMessage.getContent());
        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
